import { ProductList, ConnectState, ConnectProps, CartModelState } from '@/models/types'
import React, { ReactElement, useCallback } from 'react'
import { Link, connect, history } from 'umi'
import styles from './index.less'
import classnames from 'classnames'
import { postEditCart } from '@/servers/cart'
import { Toast } from 'antd-mobile'
/**
 * connect
 */
interface CartAndProps extends ConnectProps {
    product: ProductList,
    cart: CartModelState
}

function CartAndBuy({ product, cart, dispatch }: CartAndProps): ReactElement {
    /**
     * editCart
     * Toast.success 弹出提示框
     * 
     */
    const addToCart = useCallback(
        () => {
            if (product.id) {
                /**进行服务端请求 */
                postEditCart({ id: product.id, increment: 1 }).then(res => Toast.success(product.title + '已加入购物车'))
            }
        },
        [product],
    )
    /**
     * dispatch 
     *  type: 'cart/saveCart'
     * 保存立即购买的当前产品信息
     * cart信息需要在/confirmBill里面显示，所以存到model里，方便数据共享
     * history.push('/confirmBill')
     */
    const goBuy = useCallback(async () => {
        await dispatch({
            type: 'cart/saveCart',
            payload: {
                data: [{ ...product, count: 1, checked: true, img: product.imgs[0] }]
            }
        })
        history.push('/confirmBill')
    }, [product])
    /**
     * Link to='/cart'
     */
    return (
        <div className={styles.main}>
            <Link to='/cart' className={classnames(styles.cart)}>
                <span className='iconfont icon-3 font16'></span>
                <p className={styles.title}>购物车</p>
            </Link>
            <div
                className={classnames(styles.addCart, styles.btn)}
                onClick={addToCart}>
                加入购物车
            </div>
            <div
                className={classnames(styles.buyNow, styles.btn)}
                onClick={goBuy}
            >立即购买</div>
        </div>
    )
}
export default connect(({ cart }: ConnectState) => ({ cart }))(CartAndBuy)